import React from 'react';

export const Input = function ({ onChange, value }) {
  return (
    <input className="input" onChange={(e) => onChange && onChange(e.target.value)} value={value} />
  );
}
/* 给Component 增加标签 */
Input.displayName = 'input';

export const FormItem = function (props) {
  const { children, name, handleChange, value, label } = props;
  const onChange = (value) => {
    handleChange(name, value);
  };
  return (
    <div className="form">
      <span className="label">{label}:</span>
      {React.isValidElement(children) && children.type.displayName === 'input'
        ? React.cloneElement(children, { onChange, value })
        : null}
    </div>
  );
};
FormItem.displayName = 'formItem';

export class Form extends React.Component {
  state = {
    formData: {},
  };

  submitForm = (cb) => {
    cb && cb(this.state.formData);
  };

  resetForm = () => {
    const { formData } = this.state;
    Object.keys(formData).forEach((item) => {
      formData[item] = '';
    });
    this.setState({
      formData,
    });
  };

  setValue = (name, value) => {
    this.setState({
      formData: {
        ...this.state.formData,
        [name]: value,
      },
    });
  };

  render() {
    const { children } = this.props;
    const renderChildren = [];
    React.Children.forEach(children, (child) => {
      console.log(child);
      if (child.type.displayName === 'formItem') {
        const { name } = child.props;
        /* 克隆`FormItem`节点，混入改变表单单元项的方法 */
        const Children = React.cloneElement(child, {
          key: name /* 加入key 提升渲染效果 */,
          handleChange: this.setValue /* 用于改变 value */,
          value: this.state.formData[name] || '' /* value 值 */,
        });
        renderChildren.push(Children);
      }
    });
    return renderChildren;
  }
}
